<template>
  <div class="seller-product-manage">
    <!-- 主要内容区域 -->
    <div class="main-content">

      <!-- 登录提示 -->
      <div v-if="!isLoggedIn" class="login-prompt">
        <div class="login-prompt-icon">🔐</div>
        <h3>请先登录</h3>
        <p>您需要登录商家账户才能查看和管理店铺信息</p>
        <div class="login-prompt-actions">
          <button class="btn-primary" @click="goToLogin">商家登录</button>
          <button class="btn-cancel" @click="goToRegister">注册商家</button>
        </div>
      </div>

      <div v-if="isLoggedIn" class="content-wrapper">
        <div class="seller-info-container">
          <div class="info-header">
            <div class="shop-avatar">
              <img v-if="sellerInfo.logoUrl" :src="sellerInfo.logoUrl" alt="店铺Logo" class="logo-img" />
              <div v-else class="logo-placeholder">🏪</div>
            </div>
            <div class="shop-basic-info">
              <h2 class="shop-name">{{ sellerInfo.shopName || '店铺名称' }}</h2>
            </div>
            <button class="btn-edit" @click="handleEdit">
              <i class="icon">✏️</i>
              编辑信息
            </button>
          </div>

          <div class="info-content">
            <div class="info-section">
              <h3 class="section-title">基本信息</h3>
              <div class="info-grid">
                <div class="info-item">
                  <label>联系人</label>
                  <span class="info-value">{{ sellerInfo.contactPerson || '未设置' }}</span>
                </div>
                <div class="info-item">
                  <label>联系电话</label>
                  <span class="info-value">{{ sellerInfo.contactPhone || '未设置' }}</span>
                </div>
                <div class="info-item">
                  <label>店铺地址</label>
                  <span class="info-value address-value">{{ sellerInfo.address || '未设置' }}</span>
                </div>

              </div>
            </div>


          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="!loading && !sellerInfo.id" class="empty-state">
          <div class="empty-icon">👤</div>
          <p>暂无商家信息</p>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p>加载中...</p>
        </div>
      </div>
    </div>
  </div>
  
  <!-- 编辑表单弹窗 -->
  <div v-if="showEditForm" class="edit-modal-overlay" @click.self="handleCancel">
    <div class="edit-modal">
      <div class="modal-header">
        <h3>编辑商家信息</h3>
        <button class="close-btn" @click="handleCancel">×</button>
      </div>
      
      <div class="modal-body">
        <div class="form-group logo-group">
          <label>店铺Logo</label>
          <div class="logo-upload-container">
            <div class="logo-preview">
              <img 
                v-if="tempLogoUrl" 
                :src="tempLogoUrl" 
                alt="店铺Logo预览" 
                class="logo-preview-img"
              />
              <div v-else class="logo-placeholder">
                🏪
              </div>
            </div>
            <input 
              ref="logoInput"
              type="file" 
              accept="image/*" 
              class="logo-input" 
              @change="handleLogoSelect"
            />
            <button 
              type="button" 
              class="change-logo-btn" 
              @click="$refs.logoInput.click()"
              :disabled="submitting"
            >
              更换Logo
            </button>
          </div>
        </div>
        
        <div class="form-group">
          <label for="shopName">店铺名称</label>
          <input 
            id="shopName"
            v-model="editForm.shopName" 
            type="text" 
            class="form-input"
            placeholder="请输入店铺名称"
          />
        </div>
        
        <div class="form-group">
          <label for="contactPerson">联系人</label>
          <input 
            id="contactPerson"
            v-model="editForm.contactPerson" 
            type="text" 
            class="form-input"
            placeholder="请输入联系人姓名"
          />
        </div>
        
        <div class="form-group">
          <label for="contactPhone">联系电话</label>
          <input 
            id="contactPhone"
            v-model="editForm.contactPhone" 
            type="tel" 
            class="form-input"
            placeholder="请输入联系电话"
          />
        </div>
        
        <div class="form-group">
          <label for="address">店铺地址</label>
          <textarea 
            id="address"
            v-model="editForm.address" 
            class="form-input"
            placeholder="请输入店铺地址"
            rows="3"
          ></textarea>
        </div>
      </div>
      
      <div class="modal-footer">
        <button class="btn-cancel" @click="handleCancel" :disabled="submitting">
          取消
        </button>
        <button class="btn-submit" @click="handleSubmit" :disabled="submitting">
          {{ submitting ? '提交中...' : '确定' }}
        </button>
      </div>
    </div>
  </div>
</template>

<script>
import { querySellerById, updateMessage, updateLogo } from '../api/seller'

export default {
  name: 'SellerInfo',
  computed: {
    // 检查商家登录状态
    isLoggedIn() {
      return !!localStorage.getItem('sellerId')
    }
  },
  data() {
    return {
      sellerInfo: {},
      loading: true,
      showEditForm: false,
      editForm: {
        id: null,
        shopName: '',
        contactPerson: '',
        contactPhone: '',
        address: ''
      },
      submitting: false,
      logoFile: null,
      tempLogoUrl: ''
    }
  },
  mounted() {
    // 只在登录状态下才获取商家信息
    if (this.isLoggedIn) {
      this.fetchSellerInfo()
    }
  },
  methods: {
    async fetchSellerInfo() {
      try {
        this.loading = true
        // 从localStorage获取商家ID
        const sellerId = localStorage.getItem('sellerId')
        if (!sellerId) {
          this.$message.error('请先登录')
          return
        }

        // 调用接口获取商家信息
        const response = await querySellerById(parseInt(sellerId))

        // 存储返回的商家信息
        this.sellerInfo = response || {}

        // 更新本地存储中的商家信息
        if (this.sellerInfo.logoUrl) {
          localStorage.setItem('logoUrl', this.sellerInfo.logoUrl)
        }
        if (this.sellerInfo.shopName) {
          localStorage.setItem('shopName', this.sellerInfo.shopName)
        }
      } catch (error) {
        console.error('获取商家信息失败:', error)
        this.$message.error('获取商家信息失败，请稍后重试')
      } finally {
        this.loading = false
      }
    },

    handleEdit() {
      // 打开编辑表单
      this.editForm = {
        id: this.sellerInfo.id || parseInt(localStorage.getItem('sellerId')),
        shopName: this.sellerInfo.shopName || '',
        contactPerson: this.sellerInfo.contactPerson || '',
        contactPhone: this.sellerInfo.contactPhone || '',
        address: this.sellerInfo.address || ''
      }
      this.tempLogoUrl = this.sellerInfo.logoUrl || ''
      this.logoFile = null
      this.showEditForm = true
    },
    
    handleLogoSelect(event) {
      console.log('Logo文件选择事件触发')
      const file = event.target.files[0]
      if (file) {
        console.log('选择的文件信息:', {
          name: file.name,
          size: file.size,
          type: file.type
        })
        
        // 验证文件类型
        const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/jpg']
        if (!validTypes.includes(file.type)) {
          console.warn('文件类型验证失败:', file.type)
          this.$message.error('请选择有效的图片文件（JPG、PNG、GIF）')
          return
        }
        
        // 验证文件大小（最大2MB）
        if (file.size > 2 * 1024 * 1024) {
          console.warn('文件大小验证失败:', file.size)
          this.$message.error('图片大小不能超过2MB')
          return
        }
        
        console.log('文件验证通过，准备设置预览')
        this.logoFile = file
        // 创建临时预览URL
        if (this.tempLogoUrl) {
          console.log('清理旧的预览URL')
          URL.revokeObjectURL(this.tempLogoUrl)
        }
        
        try {
          this.tempLogoUrl = URL.createObjectURL(file)
          console.log('预览URL创建成功')
        } catch (urlError) {
          console.error('创建预览URL失败:', urlError)
          this.$message.error('无法预览图片，请重试')
          this.logoFile = null
          return
        }
      }
      
      // 清空文件输入，允许重新选择相同的文件
      event.target.value = ''
    },
    
    async handleSubmit() {
      // 简单验证
      if (!this.editForm.shopName) {
        this.$message.error('店铺名称不能为空')
        return
      }
      
      if (!this.editForm.contactPerson) {
        this.$message.error('联系人不能为空')
        return
      }
      
      if (!this.editForm.contactPhone) {
        this.$message.error('联系电话不能为空')
        return
      }
      
      if (!this.editForm.address) {
        this.$message.error('店铺地址不能为空')
        return
      }
      
      try {
        this.submitting = true
        
        // 如果选择了新的Logo，先上传Logo
        if (this.logoFile) {
          console.log('开始上传Logo，文件信息:', {
            name: this.logoFile.name,
            size: this.logoFile.size,
            type: this.logoFile.type,
            isFileObject: this.logoFile instanceof File,
            sellerId: this.editForm.id
          })
          
          try {
            // 显式检查logoFile是否为有效的File对象
            if (!(this.logoFile instanceof File)) {
              throw new Error('logoFile不是有效的File对象')
            }
            
            await updateLogo(this.logoFile, this.editForm.id)
            console.log('Logo上传成功')
          } catch (logoError) {
            console.error('Logo上传失败:', logoError)
            this.$message.error('Logo上传失败，请检查文件格式和大小后重试')
            this.submitting = false
            return
          }
        }
        
        // 更新其他信息
        console.log('开始更新商家信息:', this.editForm)
        await updateMessage(this.editForm)
        console.log('商家信息更新成功')
        
        this.$message.success('更新成功')
        this.showEditForm = false
        // 重新加载商家信息
        this.fetchSellerInfo()
      } catch (error) {
        console.error('更新商家信息失败:', error)
        this.$message.error('更新失败，请稍后重试')
      } finally {
        this.submitting = false
        // 清理临时URL
        if (this.tempLogoUrl && this.logoFile) {
          URL.revokeObjectURL(this.tempLogoUrl)
        }
      }
    },
    
    handleCancel() {
      this.showEditForm = false
      // 重置表单
      this.editForm = {
        id: null,
        shopName: '',
        contactPerson: '',
        contactPhone: '',
        address: ''
      }
      // 清理临时URL和文件
      if (this.tempLogoUrl && this.logoFile) {
        URL.revokeObjectURL(this.tempLogoUrl)
      }
      this.logoFile = null
      this.tempLogoUrl = ''
    },

    // 跳转到商家登录页面
    goToLogin() {
      this.$router.push('/seller-login')
    },

    // 跳转到商家注册页面
    goToRegister() {
      this.$router.push('/seller-login') // 商家注册通常在登录页面
    }
  }
}
</script>

<style scoped>
.seller-info-container {
  height: 99vh;
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.info-header {
  display: flex;
  align-items: center;
  gap: 20px;
  padding: 30px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  justify-content: space-between;
}

.shop-avatar {
  width: 100px;
  height: 100px;
  border-radius: 50%;
  overflow: hidden;
  background: rgba(255, 255, 255, 0.2);
  border: 4px solid rgba(255, 255, 255, 0.3);
  display: flex;
  align-items: center;
  justify-content: center;
}

.logo-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.logo-placeholder {
  font-size: 48px;
}

.shop-basic-info {
  flex: 1;
}

.shop-name {
  margin: 0 0 10px 0;
  font-size: 28px;
  font-weight: 700;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
}

.shop-id {
  font-size: 14px;
  opacity: 0.9;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.info-content {
  padding: 30px;
}

.info-section {
  margin-bottom: 30px;
}

.section-title {
  margin: 0 0 20px 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
  padding-bottom: 10px;
  border-bottom: 2px solid #f0f0f0;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.info-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.info-item label {
  font-size: 14px;
  font-weight: 600;
  color: #666;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.info-value {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.address-value {
  line-height: 1.6;
}



.btn-edit {
  padding: 12px 24px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  flex-shrink: 0;
}

.btn-edit:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.btn-edit:active {
  transform: translateY(0);
}

/* 空状态和加载状态样式 */
.empty-state,
.loading-state {
  text-align: center;
  padding: 80px 20px;
  color: #909399;
}

.empty-icon {
  font-size: 80px;
  margin-bottom: 20px;
  opacity: 0.5;
}

.empty-state p {
  font-size: 18px;
  margin: 0;
}

.loading-spinner {
  width: 50px;
  height: 50px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #667eea;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 20px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-state p {
  font-size: 16px;
  margin: 0;
}

/* 编辑表单弹窗样式 */
.edit-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  padding: 20px;
}

.edit-modal {
  background: white;
  border-radius: 12px;
  width: 100%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.3);
  animation: modalFadeIn 0.3s ease;
}

@keyframes modalFadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 1px solid #f0f0f0;
}

.modal-header h3 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 28px;
  cursor: pointer;
  color: #999;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s ease;
}

.close-btn:hover {
  background: #f5f5f5;
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  font-weight: 600;
  color: #666;
}

.form-input {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  transition: all 0.3s ease;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.form-input::placeholder {
  color: #999;
}

/* Logo上传相关样式 */
.logo-group {
  text-align: center;
  margin-bottom: 30px;
}

.logo-upload-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
}

.logo-preview {
  width: 120px;
  height: 120px;
  border-radius: 50%;
  overflow: hidden;
  border: 3px dashed #ddd;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  transition: all 0.3s ease;
}

.logo-preview:hover {
  border-color: #667eea;
  background: #f0f0ff;
}

.logo-preview-img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.logo-placeholder {
  font-size: 48px;
  color: #999;
}

.logo-input {
  display: none;
}

.change-logo-btn {
  padding: 10px 20px;
  background: #f0f0f0;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.change-logo-btn:hover:not(:disabled) {
  background: #667eea;
  color: white;
  border-color: #667eea;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.change-logo-btn:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 20px;
  border-top: 1px solid #f0f0f0;
  background: #fafafa;
  border-radius: 0 0 12px 12px;
}

.btn-cancel {
  padding: 10px 20px;
  background: white;
  color: #666;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-cancel:hover:not(:disabled) {
  background: #f5f5f5;
  border-color: #999;
}

.btn-submit {
  padding: 10px 20px;
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
}

.btn-submit:hover:not(:disabled) {
  background: #764ba2;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.3);
}

.btn-submit:disabled,
.btn-cancel:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* 登录提示样式 */
.login-prompt {
  text-align: center;
  padding: 60px 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
  max-width: 500px;
  margin: 40px auto;
}

.login-prompt-icon {
  font-size: 64px;
  color: #409eff;
  margin-bottom: 20px;
}

.login-prompt h3 {
  color: #333;
  font-size: 24px;
  margin-bottom: 12px;
  font-weight: 600;
}

.login-prompt p {
  color: #666;
  font-size: 16px;
  margin-bottom: 30px;
  line-height: 1.5;
}

.login-prompt-actions {
  display: flex;
  gap: 15px;
  justify-content: center;
  flex-wrap: wrap;
}

.login-prompt-actions button {
  padding: 12px 24px;
  font-size: 16px;
  border-radius: 6px;
  min-width: 120px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .info-header {
    flex-direction: column;
    text-align: center;
    padding: 20px;
  }

  .shop-avatar {
    width: 80px;
    height: 80px;
  }

  .shop-name {
    font-size: 24px;
  }

  .info-content {
    padding: 20px;
  }

  .info-grid {
    grid-template-columns: 1fr;
    gap: 15px;
  }

  .info-item {
    padding: 12px;
  }

  .btn-edit {
    width: 100%;
    justify-content: center;
  }
}
</style>
